package fi.foyt.cs.persistence.dao.items;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.items.StashedItem;

public class StashedItemDAO extends GenericDAO<StashedItem> {

  public StashedItem create(Long userId, Long sceneId, Long itemId, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      StashedItem stashedItem = new StashedItem();
      stashedItem.setUserId(userId);
      stashedItem.setSceneId(sceneId);
      stashedItem.setItemId(itemId);
      stashedItem.setCount(count);
      entityManager.persist(stashedItem);
      entityManager.getTransaction().commit();
      return stashedItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  public StashedItem findByUserIdAndItemIdAndSceneId(Long userId, Long itemId, Long sceneId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from StashedItem o where userId = :userId and itemId = :itemId and sceneId = :sceneId");
    query.setParameter("userId", userId);
    query.setParameter("itemId", itemId);
    query.setParameter("sceneId", sceneId);
    return getSingleResult(query);
  }

  @SuppressWarnings("unchecked")
  public List<StashedItem> listByUserId(Long userId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from StashedItem o where userId = :userId");
    query.setParameter("userId", userId);
    return query.getResultList();
  }

  @SuppressWarnings("unchecked")
  public List<StashedItem> listByUserIdAndSceneId(Long userId, Long sceneId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from StashedItem o where userId = :userId and sceneId = :sceneId");
    query.setParameter("userId", userId);
    query.setParameter("sceneId", sceneId);
    return query.getResultList();
  }

  public StashedItem updateCount(StashedItem stashedItem, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      stashedItem.setCount(count);
      stashedItem = entityManager.merge(stashedItem);
      entityManager.getTransaction().commit();

      return stashedItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
}
